﻿
using EmitMapper;
using EmitMapper.MappingConfiguration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Framework.Common
{
    public class Mapper
    {
        #region MapNew

        /// <summary>
        /// 将对象映射到一个新的对象
        /// </summary>
        /// <param name="from">源对象</param>
        /// <param name="ignoreMembers">忽略属性列表</param>
        /// <returns></returns>
        public static TTo MapNew<TFrom, TTo>(TFrom from, params string[] ignoreMembers)
        {
            if (ignoreMembers == null)
                return ObjectMapperManager.DefaultInstance.GetMapper<TFrom, TTo>().Map(from);
            return MapNew<TFrom, TTo>(from, c => c.IgnoreMembers<TFrom, TTo>(ignoreMembers));
        }

        /// <summary>
        /// 将对象映射到一个新的对象
        /// </summary>
        /// <param name="from">源对象</param>
        /// <param name="config">配置</param>
        /// <returns></returns>
        public static TTo MapNew<TFrom, TTo>(TFrom from, Action<DefaultMapConfig> config)
        {
            if (config == null)
            {
                return ObjectMapperManager.DefaultInstance.GetMapper<TFrom, TTo>().Map(from);
            }
            var mapConfig = new DefaultMapConfig();
            config(mapConfig);
            return ObjectMapperManager.DefaultInstance.GetMapper<TFrom, TTo>(mapConfig).Map(from);
        }

        #endregion

        /// <summary>
        /// 将对象映射到一个现有对象
        /// </summary>
        /// <param name="from">源对象</param>
        /// <param name="to">目标对象</param>
        public static void MapExisting<TFrom, TTo>(TFrom from, TTo to)
        {
            MapExisting<TFrom, TTo>(from, to, string.Empty);
        }

        /// <summary>
        /// 将对象映射到一个现有对象
        /// </summary>
        /// <param name="from">源对象</param>
        /// <param name="to">目标对象</param>
        /// <param name="ignoreMembers">忽略属性列表</param>
        public static void MapExisting<TFrom, TTo>(TFrom from, TTo to, params string[] ignoreMembers)
        {
            if (ignoreMembers == null)
            {
                ObjectMapperManager.DefaultInstance.GetMapper<TFrom, TTo>().Map(from, to);
                return;
            }
            MapExisting<TFrom, TTo>(from, to, c => c.IgnoreMembers<TFrom, TTo>(ignoreMembers));
        }

        public static void MapExisting<TFrom, TTo>(TFrom from, TTo to, Action<DefaultMapConfig> config)
        {
            if (config == null)
            {
                ObjectMapperManager.DefaultInstance.GetMapper<TFrom, TTo>().Map(from, to);
                return;
            }
            var mapConfig = new DefaultMapConfig();
            config(mapConfig);
            ObjectMapperManager.DefaultInstance.GetMapper<TFrom, TTo>(mapConfig).Map(from, to);
        }


    }
}
